package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeEvalutionExpert;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 商务标评审-主要材料评审计算
 * @author: xiayf
 * @date: 2019-10-15 14:05
 */
public class MainMaterialsJob implements StepJobJdbcFactory {

    private static Logger log = Logger.getLogger(MainMaterialsJob.class);

    private JdbcTemplateService jdbcTemplateService;

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layouCod) throws Exception {
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            paramMap.put("submitCode", submitCode);
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            RowMapper<BeSectionInfo> rm = BeanPropertyRowMapper.newInstance(BeSectionInfo.class);
            BeSectionInfo beSectionInfo = jdbcTemplateService.selectForObject(" select td_projectId from be_section_info where seq_id=:sectionId ", paramMap, rm);
            paramMap.put("tdProjectId", beSectionInfo.getTdProjectid());
            String sqlStr = " SELECT a.enterprise_id enterpriseId,SUM(a.rightCount) rightCount FROM(  " +
                    "  SELECT tb.enterprise_id, " +
                    "  CASE WHEN (zb.bali_Code = tb.blfx_Code AND zb.bali_Name = tb.blfx_Name AND zb.bali_Spec = tb.blfx_Spec AND zb.bali_Unit = tb.blfx_Unit)   " +
                    "  THEN 1 ELSE 0 END AS rightCount  " +
                    "  FROM td_BasicList zb  " +
                    "  LEFT JOIN td_BasicListFX_Bid tb ON zb.bali_ProjectID=tb.blfx_ProjectID AND zb.bali_BasicListID=tb.blfx_BasicListID  " +
                    "  WHERE tb.blfx_ProjectID=:tdProjectId AND zb.bali_State='3'  " +
                    "  UNION ALL  " +
                    "  SELECT tb.enterprise_id,  " +
                    "  CASE WHEN (zb.bali_Code = tb.blfx_Code AND zb.bali_Name = tb.blfx_Name AND zb.bali_Spec = tb.blfx_Spec AND zb.bali_Unit = tb.blfx_Unit AND zb.bali_Price = tb.blfx_Price)   " +
                    "  THEN 1 ELSE 0 END AS rightCount  " +
                    "  FROM td_BasicList zb  " +
                    "  LEFT JOIN td_BasicListFX_Bid tb ON zb.bali_ProjectID=tb.blfx_ProjectID AND zb.bali_BasicListID=tb.blfx_BasicListID  " +
                    "  WHERE tb.blfx_ProjectID=:tdProjectId AND zb.bali_State IN('1','2')  " +
                    "  ) a  " +
                    "  GROUP BY a.enterprise_id";
            List<Map<String, Object>> enterList = jdbcTemplateService.selectForList(sqlStr, paramMap);
            //保存计算结果
            saveResult(paramMap, enterList);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****计算商务标评审-主要材料评审失败*****");
        }
    }

    private void saveResult(Map<String, Object> paramMap, List<Map<String, Object>> enterList) throws Exception {
        try {
            RowMapper<BeSectionExpertInfo> rm1 = BeanPropertyRowMapper.newInstance(BeSectionExpertInfo.class);
            List<BeSectionExpertInfo> beSectionExpertInfoList = jdbcTemplateService.selectForList(" select " +
                    "    seq_id, section_id, name, login_name, card_no, work_unit, phone, expert_type, area_type, " +
                    "    is_avoid, avoid_reason, is_manager, update_time, create_time " +
                    "    from be_section_expert_info " +
                    "    where section_id=:sectionId", paramMap, rm1);
            RowMapper<BeSectionStep> rm2 = BeanPropertyRowMapper.newInstance(BeSectionStep.class);
            BeSectionStep beSectionStep = jdbcTemplateService.selectForObject(" select " +
                    "    seq_id, section_id, step_code, step_name, parent_code, order_num, step_url, related_step_code,  " +
                    "    related_layout_code, related_column_code, related_step_id, create_time, update_time,load_function" +
                    "    from be_section_step " +
                    "     where section_id=:sectionId and step_code = '63'", paramMap, rm2);
            paramMap.put("sectionStepId", beSectionStep.getSeqId());
            paramMap.put("relatedColumnCode", beSectionStep.getRelatedColumnCode());
            //查询招标材料要求数
            List<Map<String, Object>> list = jdbcTemplateService.selectForList("SELECT bali_BasicListID FROM td_BasicList WHERE bali_ProjectID=:tdProjectId",
                    paramMap);
            int count = 0;
            if (list != null && !list.isEmpty()) {
                count = list.size();
            }
            //删除已存在结果
            jdbcTemplateService.update(" DELETE FROM be_evalution_expert WHERE section_id=:sectionId AND section_step_id=:sectionStepId " +
                    " AND submit_code=:submitCode AND column_code=:relatedColumnCode ", paramMap);
            jdbcTemplateService.update(" DELETE FROM be_evalution_expert WHERE section_id=:sectionId AND section_step_code='63' " +
                    "AND submit_code=:submitCode ", paramMap);
            List<BeEvalutionExpert> beEvalutionExpertList = new ArrayList<>();
            BeEvalutionExpert beEvalutionExpert = null;
            for (BeSectionExpertInfo beSectionExpertInfo : beSectionExpertInfoList) {
                for (Map<String, Object> map : enterList) {
                    //未响应材料数=招标要求材料数-投标响应材料数
                    int errorCount = count - OConvertUtils.getInt(map.get("rightCount"));
                    //招标要求材料数
                    beEvalutionExpert = new BeEvalutionExpert();
                    beEvalutionExpert.setSeqId(IdsUtil.uuid());
                    beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
                    beEvalutionExpert.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beEvalutionExpert.setColumnCode("rightCount");
                    beEvalutionExpert.setColumnValue(OConvertUtils.getString(count));
                    beEvalutionExpert.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
                    beEvalutionExpert.setSectionStepId(beSectionStep.getSeqId());
                    beEvalutionExpert.setSectionStepCode(beSectionStep.getStepCode());
                    beEvalutionExpert.setLayoutCode("Top");
                    beEvalutionExpert.setSubmitCode(OConvertUtils.getString(paramMap.get("submitCode")));
                    beEvalutionExpert.setCreateTime(DateUtil.now());
                    beEvalutionExpert.setUpdateTime(DateUtil.now());
                    beEvalutionExpertList.add(beEvalutionExpert);
                    //未响应材料数
                    beEvalutionExpert = new BeEvalutionExpert();
                    beEvalutionExpert.setSeqId(IdsUtil.uuid());
                    beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
                    beEvalutionExpert.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beEvalutionExpert.setColumnCode("errorCount");
                    beEvalutionExpert.setColumnValue(OConvertUtils.getString(errorCount));
                    beEvalutionExpert.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
                    beEvalutionExpert.setSectionStepId(beSectionStep.getSeqId());
                    beEvalutionExpert.setSectionStepCode(beSectionStep.getStepCode());
                    beEvalutionExpert.setLayoutCode("Top");
                    beEvalutionExpert.setSubmitCode(OConvertUtils.getString(paramMap.get("submitCode")));
                    beEvalutionExpert.setCreateTime(DateUtil.now());
                    beEvalutionExpert.setUpdateTime(DateUtil.now());
                    beEvalutionExpertList.add(beEvalutionExpert);
                    //是否通过
                    beEvalutionExpert = new BeEvalutionExpert();
                    beEvalutionExpert.setSeqId(IdsUtil.uuid());
                    beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
                    beEvalutionExpert.setColumnCode(beSectionStep.getRelatedColumnCode());
                    if (errorCount > 0) {
                        beEvalutionExpert.setColumnValue("0");
                    } else {
                        beEvalutionExpert.setColumnValue("1");
                    }
                    beEvalutionExpert.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
                    beEvalutionExpert.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beEvalutionExpert.setSectionStepId(beSectionStep.getRelatedStepId());
                    beEvalutionExpert.setSectionStepCode(beSectionStep.getRelatedStepCode());
                    beEvalutionExpert.setLayoutCode(beSectionStep.getRelatedLayoutCode());
                    beEvalutionExpert.setSubmitCode(OConvertUtils.getString(paramMap.get("submitCode")));
                    beEvalutionExpert.setCreateTime(DateUtil.now());
                    beEvalutionExpert.setUpdateTime(DateUtil.now());
                    beEvalutionExpertList.add(beEvalutionExpert);
                }
            }
            //批量转数组
            SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(beEvalutionExpertList);
            jdbcTemplateService.bathInsert(" insert into be_evalution_expert (seq_id, section_step_id, section_id, " +
                    "    column_code, expert_id, column_value,submit_code,row_key,layout_code,enterprise_id,section_step_code,create_time, " +
                    "    update_time) " +
                    "    values(:seqId, :sectionStepId, :sectionId,:columnCode, :expertId, :columnValue,:submitCode,:rowKey," +
                    "   :layoutCode,:enterpriseId,:sectionStepCode,:createTime,:updateTime)", beanSources);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****保存商务标评审-主要材料评审结果失败*****");
        }
    }
}
